<?php


echo "<html><head></head><body>";

function form($error)
{

	echo"<form name=\"form1\" method=\"post\">";

		if($error)
		{
			echo "<h1>".$error."</h1>"; 
		}
		else
		{
			echo "<h1>Member Login</h1>"; 
		} 
		echo "Username: <input name=\"username\" type=\"text\" id=\"username\"><p>
			Password: <input name=\"password\" type=\"password\" id=\"password\"><p>
			<input type=\"submit\" name=\"Submit\" value=\"Login\">
			</form>";
}
function login_check($username,$password)
{

	$db = mysql_connect("localhost", "vandes4_root", root) or die('Script Could not connect to database');
	mysql_select_db("vandes4_PROJECT",$db);
	
	$login_check = false;
	
	# THE WILL HELP YOU WITH SQL INJECTION
	$password = mysql_real_escape_string(md5($password));
	$username = mysql_real_escape_string($username);

	$sql = "SELECT * FROM users WHERE username = '".$username."'";

	$result = mysql_query($sql ,$db);
	if ($myrow = mysql_fetch_array($result))
	{
		if($username == $myrow['username'] && $password == md5($myrow['password']))
		{
			$login_check = true;
		}
	}

	return $login_check;
}
if(isset($_REQUEST['Submit']))
{
	if(!$_POST['username']|| !$_POST['password'] )
	{
		$error = 'Error: Username Required';
		echo form($error);
	}

	else
	{
		if (login_check($_POST['username'],$_POST['password']))
		{
			session_start();
			$_SESSION['loggedIn'] = 'youAreLogged';  
			$_SESSION['userName'] = $username;  
			echo 'Congratulations! You are now logged in<br>';
			echo ("<script type='text/javascript'>
			<!--
			window.location = 'redirect.html'
			//-->
			</script>
			");
			echo '<a href=\"logout.php\">Log out</a>';

			session_register("username");
			session_register("password");
		}
		else
		{
			$error = "Invalid username or password, try again";
			echo form($error);
		}
	}
}
else
{
	if($_GET['logout'])
	{
		session_destroy();
		$error = "Logged Out Success - Try Again"; 
		echo form($error); 
	} 
	else 
	{
		if ($_SESSION['username']) 
		{
			if (login_check($_SESSION['username'],$_SESSION['password'])) 
			{
				echo '<a href=\"?logout=yes\">Log out</a>'; 
			}
			else
			{
				$error = "Please Login"; echo form($error); 
			}
		}
		else 
		{ 
			$error = "Welcome, Please Login";
			echo form($error); 
		}
	}
} 
echo "</body></html>";
?>